from maix import camera , display , image , app , uart
import struct

# 全局变量区域
threshold = [[7, 30, -5, 17, -15, 5]]

rois =  [
            [60,160,200,60],
            [60,80,200,60],
            [60,0,200,60]
        ]

weights = [ 0.5 , 0.3 ,0.2 ]

turn_flag = 0


# 函数定义区域
def uart_send(serial:uart.UART,head,data):
    send_data = struct.pack("<Bh",head,data)
    serial.write(send_data)

def Uart_Callback(uart,data):
    global turn_flag
    rx_len = len(data)
    if rx_len == 2:
        if data[0] == 0x55:
            turn_flag = data[1]
            print(turn_flag)


# 类实例创造区域
cam = camera.Camera(320,240)
disp = display.Display()
device1 = "/dev/ttyS0"          # 示例的串口名称                        此串口设备名称为串口0
serial = uart.UART(device1,115200)  #创建串口对象，八位数据，无检验，一位停止
serial.set_received_callback(Uart_Callback)



while not app.need_exit():
    img = cam.read()
    img.draw_string(0,0,f"task is {turn_flag}")
    err = 0
    find_count = 0

    for i in range(3):
        # 查找上中下方roi区域的色块
        blobs = img.find_blobs(threshold,roi=rois[i],area_threshold = 200 , pixels_threshold=200)
        if blobs:
            if turn_flag == 0:
                blob = max(blobs,key=lambda blob:blob.cx())
                
            else:
                blob = min(blobs,key=lambda blob:blob.cx())
            img.draw_rect(blob.x(),blob.y(),blob.w(),blob.h(),image.COLOR_RED,thickness=3)
            cx = blob.cx()
            err += blob.cx()
            find_count += 1  
    

    '''
    if find_count == 3:
        err = ( err - img.width()/2 ) 
        print("三个色块都找到了")
    elif find_count == 2:
        print("两个色块找到了")
    elif find_count == 1:
        err = (   (err / 0.6) - (img.width()/2)  )
        print("只找到最下面一个色块")
    else :
        err = 30
        print("没有找到线")
    '''
    if find_count != 0:
        err =( (err/find_count) - (img.width()/2) )
    else:
        err = 30
    print(f"找到的色块数为{find_count}")

    uart_send(serial,0xaa,int(err))
    
    img.draw_string(0,40,f"err is {int(err)}")
    disp.show(img)